package com.example.myapplication4;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    ProgressBar progressBar;
    MyTask myTask;
    private TextView pm25TextView;
    private TextView humidityTextView;
    private TextView cityNameTextView;
    private TextView tempTextView;
    private Map<String,String> map=new HashMap<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        this.tempTextView = findViewById(R.id.tv_temp);
        this.humidityTextView = findViewById(R.id.tv_humidity);
        this.pm25TextView = findViewById(R.id.tv_pm25);
        this.cityNameTextView = findViewById(R.id.tv_cityname);

        String[] cityCodeArray = getResources().getStringArray(R.array.cityCode);

        String[] cityNameArray = getResources().getStringArray(R.array.cityName);
        for (int i = 0; i < cityNameArray.length; i++) {
            map.put(cityNameArray[i],cityCodeArray[i]);
        }
    }

    public void download(View view) {
//        执行文件下载等耗时操作
//        现象：界面会卡死3秒
//        异步任务AsyncTask 执行耗时操作
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        2、实例化任务   调用执行方法
        myTask = new MyTask();
        try {
            myTask.execute(new URL("http://www.baidu.com"));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    public void cance(View view) {
        myTask.cancel(false);
        progressBar.setProgress(0);
    }

    public void getWeather(View view) {
        EditText editText = findViewById(R.id.et_ChengShi);
        GetWeatherTask GetWeatherTask = new GetWeatherTask();
        try {
            GetWeatherTask.execute(new URL("https://api.help.bj.cn/apis/weather/?id="+map.get(editText.getText().toString())));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }


    //      新建异步任务   获取天气数据并显示到界面上
    private  class GetWeatherTask extends AsyncTask<URL, Integer, String>

{
    @Override
    protected String doInBackground(URL... urls) {
//        这里  获取数据
        try {
            return getWeather(urls[0]);
        } catch (IOException e) {
            e.printStackTrace();
        }
       return null;
    }

    @Override
//        任务完成后   界面更新
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Log.d("TAG","任务完成后："+s);
//        JOSN序列化    fastjson库
//        希望将JSON字符串   序列化成对象
        WeatherBean weatherBean = JSON.parseObject(s,WeatherBean.class);
        tempTextView.setText(weatherBean.getTemp());
        humidityTextView.setText(weatherBean.getHumidity());
        pm25TextView.setText(weatherBean.getPm25());
        cityNameTextView.setText(weatherBean.getCity());
    }

    private String getWeather(URL myurl) throws IOException{
//        新建网络连接
        HttpURLConnection connection = null;
        StringBuffer tempString = new StringBuffer();
        URL url = myurl;
        connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(10000);
        connection.setConnectTimeout(15000);
//        执行网络连接
        connection.connect();
//        请求网络数据
        int responseCode = connection.getResponseCode();
        if (responseCode == 200)
        {
            InputStream inputStream = connection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(inputStream));
            String responseLine = bufferedReader.readLine();
            while (responseLine!=null)
            {
                tempString.append(responseLine);
                responseLine = bufferedReader.readLine();
            }
//            打印数据
            Log.d("TAG","getWeather:"+tempString.toString());
//            关闭网络连接
            inputStream.close();
            bufferedReader.close();
            connection.disconnect();
        }
        return tempString.toString();
    }

}


    //         1、新建异步任务类  继承AsyncTask
    private class MyTask extends AsyncTask<URL,Integer,Integer>{

    @Override
//    在后台运行
    protected Integer doInBackground(URL... urls) {
        for (int i = 0; i < 100; i++){
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (isCancelled())
                    break;
                publishProgress(i);
        }
        return null;
    }

//    后台执行任务之前执行
    protected void onPreExecute() {
        super.onPreExecute();
        progressBar.setProgress(0);
    }

    @Override
//后台任务完成之后执行   也就是doInBackground 返回之后执行
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
        progressBar.setProgress(0);
    }

    @Override
//   后台任务调用publishprogress的回调   也就是会在调用publishprogress之后执行
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
//        执行进度条更新
        progressBar.setProgress(values[0]);
    }


}
}